// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: xguo

#include "coin2/strategy/umm/base.h"

#include <chrono>
#include <cmath>

namespace xguo {

void OhlcCalculator::UpdateByBbo(const Bbo& bbo) {
  timestamp_ = bbo.timestamp;
  CHECK_GT(timestamp_, 100000);

  // Calculate ohlc for the previous window.
  int64_t window_index = bbo.timestamp / window_size_;
  if (window_index > window_index_ && queue_.size() > 2) {
    OhlcEntry entry;
    entry.open = queue_.front().midp;
    auto pair = std::minmax_element(queue_.begin(), queue_.end());
    entry.low = pair.first->midp;
    entry.high = pair.second->midp;
    entry.close = queue_.back().midp;
    entry.rtn = std::log(entry.close / entry.open);
    entry.timestamp = window_index_ * window_size_;

    ohlc_.push_back(entry);
    queue_.clear();
    window_index_ = window_index;
    if (ohlc_.size() > 60) {
      ohlc_.pop_front();
    }
  }

  queue_.push_back(bbo);
}

}  // namespace xguo
